<template>
  <div v-if="visible" class="modal-overlay" @click="close">
    <div class="modal-content template-modal" @click.stop>
      <div class="modal-header">
        <h3>模板配置</h3>
        <button class="close-btn" @click="close">×</button>
      </div>
      
      <div class="modal-body">
        <div class="add-template-section">
          <button class="add-template-btn" @click="createTemplate">+ 创建模板</button>
        </div>
        
        <div class="template-table">
          <div class="table-header">
            <div class="header-cell">模板序号</div>
            <div class="header-cell">操作</div>
          </div>
          
          <div v-for="(template, index) in templates" :key="template.id" class="template-row">
            <div class="cell">
              <span v-if="editingNameTemplateId !== template.id" class="template-number">
                {{ index + 1 }} - 
                <span class="template-name" @click="startEditTemplateName(template)" title="点击编辑模板名字">
                  {{ template.name || '未命名模板' }}
                </span>
              </span>
              <div v-else class="template-name-edit">
                <span class="template-number">{{ index + 1 }} - </span>
                <input 
                  v-model="editingTemplateName" 
                  @blur="saveTemplateName(template.id)"
                  @keyup.enter="saveTemplateName(template.id)"
                  @keyup.esc="cancelEditTemplateName"
                  class="template-name-input"
                  ref="templateNameInput"
                  maxlength="50"
                />
                <button @click="saveTemplateName(template.id)" class="save-name-btn" title="保存">✓</button>
              </div>
            </div>
            
            <div class="cell">
              <div class="template-actions">
                <button class="action-btn edit-btn" @click="editTemplate(template.id)" title="编辑">✏️</button>
                <button class="action-btn copy-btn" @click="copyTemplate(template.id)" title="复制">📋</button>
                <button class="action-btn delete-btn" @click="deleteTemplate(template.id)" title="删除">🗑️</button>
              </div>
            </div>
          </div>
          
          <div v-if="templates.length === 0" class="empty-template">
            暂无模板，点击上方"创建模板"按钮添加
          </div>
        </div>
      </div>
      
      <div class="modal-footer">
        <button class="cancel-btn" @click="close">关闭</button>
        <button class="save-btn" @click="saveAllTemplates">保存</button>
      </div>
    </div>
  </div>

  <!-- 模板设计界面 -->
  <div v-if="templateDesignVisible" class="modal-overlay" @click="closeTemplateDesign">
    <div class="modal-content template-design-modal" @click.stop :style="templateModalStyle">
      <div class="modal-header draggable-header" 
           @mousedown="startDragTemplateModal"
           @mousemove="dragTemplateModal"
           @mouseup="stopDragTemplateModal">
        <h3>{{ editingTemplateId ? '编辑模板' : '创建模板' }}</h3>
        <button class="close-btn" @click="closeTemplateDesign">×</button>
      </div>
      
      <div class="template-design-body">
        <div class="task-blocks-panel">
          <div class="panel-header">
            <h4>任务块</h4>
          </div>
          <div class="task-blocks-list">
            <div 
              v-for="taskBlock in availableTaskBlocks" 
              :key="taskBlock.id"
              class="task-block-item"
              draggable="true"
              @dragstart="onDragStart($event, taskBlock)"
              :style="{ backgroundColor: taskBlock.color }"
            >
              <div class="task-block-name">{{ taskBlock.name || '未命名任务' }}</div>
              <div class="task-block-duration">{{ taskBlock.duration }}天</div>
              <!-- 隐藏设备信息显示 -->
              <!-- <div v-if="(taskBlock.requiredDevices && taskBlock.requiredDevices.length > 0)" class="task-block-device">
                设备: {{ taskBlock.requiredDevices.join(', ') }}
              </div>
              <div v-else-if="taskBlock.requiredDevice" class="task-block-device">
                设备: {{ taskBlock.requiredDevice }}
              </div> -->
            </div>
            
            <div v-if="availableTaskBlocks.length === 0" class="empty-task-blocks">
              暂无任务块，请先在任务块定义配置中创建
            </div>
          </div>
        </div>
        
        <div class="arrangement-panel">
          <div class="panel-header">
            <h4>排列区</h4>
          </div>
          <div 
            class="arrangement-area"
            @dragover="onDragOver"
            @drop="onDrop"
            @dragleave="onDragLeave"
            @scroll="onArrangementScroll"
          >
            <!-- 插入位置指示器 -->
            <div 
              v-if="dragOverArrangement && insertIndicatorIndex === 0"
              class="insert-indicator"
            ></div>
            
            <template v-for="(task, index) in arrangedTaskBlocks" :key="task.instanceId">
              <div 
                class="arranged-task-item"
                draggable="true"
                @dragstart="onArrangedTaskDragStart($event, task, index)"
                @dragover="onArrangedTaskDragOver($event, index)"
                @drop="onArrangedTaskDrop($event, index)"
                :style="{ backgroundColor: task.color }"
              >
              <div class="task-info">
                <div class="task-name">{{ task.name }}</div>
                <div class="task-duration">{{ task.duration }}天</div>
                <!-- 隐藏设备信息显示 -->
                <!-- <div v-if="(task.requiredDevices && task.requiredDevices.length > 0)" class="task-device">
                  {{ task.requiredDevices.join(', ') }}
                </div>
                <div v-else-if="task.requiredDevice" class="task-device">
                  {{ task.requiredDevice }}
                </div> -->
              </div>
              <button class="remove-task-btn" @click="removeArrangedTask(task.instanceId)">×</button>
            </div>
            
            <!-- 任务块之间的插入指示器 -->
            <div 
              v-if="dragOverArrangement && insertIndicatorIndex === index + 1"
              class="insert-indicator"
            ></div>
          </template>
            
            <div v-if="arrangedTaskBlocks.length === 0" class="drop-hint">
              拖拽任务块到此处进行排列
            </div>
          </div>
        </div>
      </div>
      
      <div class="modal-footer">
        <button class="cancel-btn" @click="closeTemplateDesign">取消</button>
        <button class="save-btn" @click="saveTemplateDesign">保存模板</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'TemplateConfiguration',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      templates: [],
      templateDesignVisible: false,
      editingTemplateId: null,
      availableTaskBlocks: [],
      arrangedTaskBlocks: [],
      loading: false,
      // 模板名字编辑相关
      editingNameTemplateId: null,
      editingTemplateName: '',
      // 模板弹窗拖动相关
      templateModalDragging: false,
      templateModalStartX: 0,
      templateModalStartY: 0,
      templateModalOffsetX: 0,
      templateModalOffsetY: 0,
      // 拖拽插入位置指示
      dragOverArrangement: false,
      insertIndicatorIndex: -1,
    }
  },
  computed: {
    templateModalStyle() {
      return {
        transform: `translate(${this.templateModalOffsetX}px, ${this.templateModalOffsetY}px)`
      }
    }
  },
  mounted() {
    this.loadTemplates()
    // 监听任务块配置更新事件，实现与任务块定义配置的同步
    window.addEventListener('taskblocks-updated', this.handleTaskBlocksUpdated)
    window.addEventListener('taskblock-day-config-changed', this.handleTaskBlockDayConfigChanged)
  },
  
  beforeDestroy() {
    // 清理事件监听器，避免内存泄漏
    window.removeEventListener('taskblocks-updated', this.handleTaskBlocksUpdated)
    window.removeEventListener('taskblock-day-config-changed', this.handleTaskBlockDayConfigChanged)
  },
  
  watch: {
    visible(newVal) {
      if (newVal) {
        // 每次打开模板配置时重新加载模板数据
        this.loadTemplates()
      }
    }
  },
  methods: {
    close() {
      this.$emit('close')
    },

    // 模板名字编辑相关方法
    startEditTemplateName(template) {
      this.editingNameTemplateId = template.id
      this.editingTemplateName = template.name || ''
      this.$nextTick(() => {
        const input = this.$refs.templateNameInput
        if (input && input.length > 0) {
          input[0].focus()
          input[0].select()
        } else if (input) {
          input.focus()
          input.select()
        }
      })
    },

    async saveTemplateName(templateId) {
      const newName = this.editingTemplateName.trim()
      if (!newName) {
        alert('模板名字不能为空')
        return
      }
      
      try {
        this.loading = true
        const response = await axios.put(`/api/templates/${templateId}/`, {
          name: newName
        })
        
        if (response.data.success || response.status === 200) {
          // 更新本地模板数据
          const template = this.templates.find(t => t.id == templateId)
          if (template) {
            template.name = newName
          }
          this.cancelEditTemplateName()
        } else {
          alert('保存模板名字失败，请重试')
        }
      } catch (error) {
        console.error('保存模板名字失败:', error)
        alert('保存模板名字失败，请重试')
      } finally {
        this.loading = false
      }
    },

    cancelEditTemplateName() {
      this.editingNameTemplateId = null
      this.editingTemplateName = ''
    },

    async saveAllTemplates() {
      try {
        this.loading = true
        // 直接关闭，不重新整理模板名称
        this.close()
      } catch (error) {
        console.error('保存模板失败:', error)
        alert('保存模板失败，请重试')
      } finally {
        this.loading = false
      }
    },

    async createTemplate() {
      try {
        // 重置为新建模式
        this.editingTemplateId = null
        this.arrangedTaskBlocks = []
        this.templateDesignVisible = true
        await this.loadAvailableTaskBlocks()
      } catch (error) {
        console.error('加载任务块失败:', error)
        alert('加载任务块失败，请重试')
      }
    },

    async editTemplate(templateId) {
      try {
        console.log('编辑模板:', templateId)
        const template = this.templates.find(t => t.id === templateId)
        if (template) {
          // 设置编辑模式
          this.editingTemplateId = templateId
          
          // 加载模板的任务块数据到排列区，确保设备信息完整
          this.arrangedTaskBlocks = template.task_blocks_layout ? template.task_blocks_layout.map(task => ({
            ...task,
            instanceId: Date.now() + Math.random(), // 为每个任务块生成新的实例ID
            // 确保设备信息完整
            requiredDevices: task.requiredDevices || [],
            requiredDevice: task.requiredDevice || '',
            deviceCapacities: task.deviceCapacities || {},
            dayConfigs: task.dayConfigs || []
          })) : []
          
          console.log('编辑模板加载的任务块:', this.arrangedTaskBlocks)
          
          // 加载可用任务块
          await this.loadAvailableTaskBlocks()
          
          // 打开模板设计界面
          this.templateDesignVisible = true
          
          // 如果有多个任务块，等待DOM更新后滚动到顶部
          this.$nextTick(() => {
            const arrangementArea = document.querySelector('.arrangement-area')
            if (arrangementArea && this.arrangedTaskBlocks.length > 0) {
              arrangementArea.scrollTop = 0
            }
          })
        }
      } catch (error) {
        console.error('编辑模板失败:', error)
        alert('编辑模板失败，请重试')
      }
    },

    async copyTemplate(templateId) {
      try {
        this.loading = true
        const response = await axios.post(`/api/templates/${templateId}/copy/`)
        if (response.data.success) {
          // 重新加载模板列表
          await this.loadTemplates()
          console.log('复制模板成功:', templateId)
        } else {
          alert('复制模板失败：' + response.data.message)
        }
      } catch (error) {
        console.error('复制模板失败:', error)
        alert('复制模板失败，请重试')
      } finally {
        this.loading = false
      }
    },

    async deleteTemplate(templateId) {
      if (confirm('确定要删除这个模板吗？')) {
        try {
          this.loading = true
          await axios.delete(`/api/templates/${templateId}/`)
          // 重新加载模板列表
          await this.loadTemplates()
          console.log('删除模板成功:', templateId)
        } catch (error) {
          console.error('删除模板失败:', error)
          alert('删除模板失败，请重试')
        } finally {
          this.loading = false
        }
      }
    },

    async reorderTemplateNames() {
      try {
        const response = await axios.post('/api/templates/reorder_names/')
        if (response.data.success) {
          console.log('重新整理模板名称成功')
        }
      } catch (error) {
        console.error('重新整理模板名称失败:', error)
        throw error
      }
    },

    async loadTemplates() {
      try {
        this.loading = true
        const response = await axios.get('/api/templates/')
        console.log('模板API响应:', response.data)
        
        // 检查响应数据结构并正确提取模板数组
        if (response.data && response.data.success && Array.isArray(response.data.data)) {
          this.templates = response.data.data
        } else if (Array.isArray(response.data)) {
          this.templates = response.data
        } else {
          console.warn('模板API返回的数据格式不正确:', response.data)
          this.templates = []
        }
        
        this.$emit('templates-updated', this.templates)
      } catch (error) {
        console.error('加载模板失败:', error)
        alert('加载模板失败，请重试')
      } finally {
        this.loading = false
      }
    },

    async loadAvailableTaskBlocks() {
      try {
        const response = await axios.get('/api/templates/available_taskblocks/')
        console.log('任务块API响应:', response.data)
        
        // 检查响应数据结构并正确提取任务块数组
        const taskBlocksData = response.data.success && Array.isArray(response.data.data) 
          ? response.data.data 
          : (Array.isArray(response.data) ? response.data : [])
        
        this.availableTaskBlocks = taskBlocksData.map(task => {
          // 解析daily_device_config字段
          let deviceConfig = {}
          if (task.daily_device_config) {
            try {
              deviceConfig = JSON.parse(task.daily_device_config)
            } catch (e) {
              console.warn('解析设备配置失败:', e)
            }
          }
          
          return {
            id: task.id,
            name: task.name,
            duration: task.duration,
            color: deviceConfig.color || task.color || '#87CEEB',
            requiredDevices: deviceConfig.devices || [],
            requiredDevice: task.requiredDevice || '',
            deviceCapacities: deviceConfig.deviceCapacities || {},
            dayConfigs: deviceConfig.dayConfigs || [],
            status: task.status
          }
        })
        
        console.log('处理后的任务块数据:', this.availableTaskBlocks)
      } catch (error) {
        console.error('加载可用任务块失败:', error)
        throw error
      }
    },



    closeTemplateDesign() {
      this.templateDesignVisible = false
      this.arrangedTaskBlocks = []
      this.editingTemplateId = null
      
      // 重置拖动状态
      this.templateModalDragging = false
      this.templateModalOffsetX = 0
      this.templateModalOffsetY = 0
      
      // 移除可能残留的事件监听器
      document.removeEventListener('mousemove', this.dragTemplateModal)
      document.removeEventListener('mouseup', this.stopDragTemplateModal)
    },

    onDragStart(event, taskBlock) {
      event.dataTransfer.setData('text/plain', JSON.stringify(taskBlock))
    },

    onDragOver(event) {
      event.preventDefault()
      
      const dragData = event.dataTransfer.getData('text/plain')
      if (dragData) {
        try {
          const parsedData = JSON.parse(dragData)
          // 只对从左侧拖拽的新任务块显示插入指示器
          if (!parsedData.isReorder) {
            this.dragOverArrangement = true
            this.insertIndicatorIndex = this.calculateInsertPosition(event)
          }
        } catch (e) {
          // 如果解析失败，可能是从左侧拖拽的任务块
          this.dragOverArrangement = true
          this.insertIndicatorIndex = this.calculateInsertPosition(event)
        }
      }
    },

    onDrop(event) {
      event.preventDefault()
      
      // 清除拖拽状态
      this.dragOverArrangement = false
      this.insertIndicatorIndex = -1
      
      const dragData = JSON.parse(event.dataTransfer.getData('text/plain'))
      
      // 如果是重新排序操作，不处理（由onArrangedTaskDrop处理）
      if (dragData.isReorder) {
        return
      }
      
      // 从左侧拖拽新任务块
      const taskBlock = dragData.taskBlock || dragData
      
      // 创建一个新的任务块实例，包含唯一的instanceId和完整的设备信息
      const newTaskInstance = {
        ...taskBlock,
        instanceId: Date.now() + Math.random(), // 唯一标识符
        // 确保设备信息完整
        requiredDevices: taskBlock.requiredDevices || [],
        requiredDevice: taskBlock.requiredDevice || '',
        deviceCapacities: taskBlock.deviceCapacities || {},
        dayConfigs: taskBlock.dayConfigs || []
      }
      
      // 计算插入位置
      const insertIndex = this.calculateInsertPosition(event)
      
      console.log('拖拽添加任务块:', newTaskInstance, '插入位置:', insertIndex)
      
      // 在指定位置插入任务块
      this.arrangedTaskBlocks.splice(insertIndex, 0, newTaskInstance)
      
      // 如果插入到末尾，滚动到底部；否则保持当前滚动位置
      this.$nextTick(() => {
        const arrangementArea = document.querySelector('.arrangement-area')
        if (arrangementArea && insertIndex === this.arrangedTaskBlocks.length - 1) {
          arrangementArea.scrollTop = arrangementArea.scrollHeight
        }
      })
    },

    removeArrangedTask(instanceId) {
      this.arrangedTaskBlocks = this.arrangedTaskBlocks.filter(task => task.instanceId !== instanceId)
    },

    onArrangedTaskDragStart(event, taskBlock, index) {
      event.dataTransfer.effectAllowed = 'move'
      const dragData = {
        isReorder: true,
        sourceIndex: index,
        taskBlock: taskBlock
      }
      event.dataTransfer.setData('text/plain', JSON.stringify(dragData))
    },

    onArrangedTaskDragOver(event, targetIndex) {
      event.preventDefault()
      event.dataTransfer.dropEffect = 'move'
    },

    onArrangedTaskDrop(event, targetIndex) {
      event.preventDefault()
      event.stopPropagation()
      
      const dragData = JSON.parse(event.dataTransfer.getData('text/plain'))
      
      if (dragData.isReorder && dragData.sourceIndex !== undefined) {
        const sourceIndex = dragData.sourceIndex
        
        if (sourceIndex !== targetIndex) {
          // 保存当前滚动位置
          const arrangementArea = document.querySelector('.arrangement-area')
          const currentScrollTop = arrangementArea ? arrangementArea.scrollTop : 0
          
          // 执行拖拽排序
          const taskToMove = this.arrangedTaskBlocks[sourceIndex]
          this.arrangedTaskBlocks.splice(sourceIndex, 1)
          this.arrangedTaskBlocks.splice(targetIndex, 0, taskToMove)
          
          // 恢复滚动位置
          this.$nextTick(() => {
            if (arrangementArea) {
              arrangementArea.scrollTop = currentScrollTop
            }
          })
        }
      }
    },

    onDragLeave(event) {
      // 检查是否真的离开了排列区域
      const rect = event.currentTarget.getBoundingClientRect()
      const x = event.clientX
      const y = event.clientY
      
      if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) {
        this.dragOverArrangement = false
        this.insertIndicatorIndex = -1
      }
    },

    onArrangementScroll(event) {
      // 处理滚动事件，如果需要的话
    },

    // 计算任务块插入位置
    calculateInsertPosition(event) {
      const arrangementArea = event.currentTarget
      const rect = arrangementArea.getBoundingClientRect()
      const mouseY = event.clientY - rect.top + arrangementArea.scrollTop
      
      // 如果没有任务块，插入到开头
      if (this.arrangedTaskBlocks.length === 0) {
        return 0
      }
      
      // 获取所有任务块元素
      const taskElements = arrangementArea.querySelectorAll('.arranged-task-item')
      
      for (let i = 0; i < taskElements.length; i++) {
        const taskElement = taskElements[i]
        const taskRect = taskElement.getBoundingClientRect()
        const taskTop = taskRect.top - rect.top + arrangementArea.scrollTop
        const taskBottom = taskTop + taskRect.height
        const taskMiddle = taskTop + taskRect.height / 2
        
        // 如果鼠标在当前任务块的上半部分，插入到当前位置之前
        if (mouseY < taskMiddle) {
          return i
        }
      }
      
      // 如果鼠标在所有任务块下方，插入到末尾
      return this.arrangedTaskBlocks.length
    },

    async saveTemplateDesign() {
      if (this.arrangedTaskBlocks.length === 0) {
        alert('请至少添加一个任务块到排列区')
        return
      }
      
      try {
        this.loading = true
        
        const taskBlocksData = this.arrangedTaskBlocks.map(task => ({
          id: task.id,
          name: task.name,
          duration: task.duration,
          color: task.color,
          requiredDevice: task.requiredDevice,
          requiredDevices: task.requiredDevices || [],
          dayConfigs: task.dayConfigs || [], // 保存按天设备配置
          deviceCapacities: task.deviceCapacities || {} // 保存设备容量配置
        }))
        
        const templateData = {
          task_blocks_layout: taskBlocksData,
          description: ''
        }
        
        if (this.editingTemplateId) {
          // 编辑模式：更新现有模板
          const template = this.templates.find(t => t.id === this.editingTemplateId)
          if (template) {
            templateData.name = template.name
            await axios.put(`/api/templates/${this.editingTemplateId}/`, templateData)
            console.log('更新模板成功:', this.editingTemplateId)
          }
        } else {
          // 新建模式：创建新模板
          const templateNumber = this.templates.length + 1
          templateData.name = `模板${templateNumber}`
          await axios.post('/api/templates/', templateData)
          console.log('创建新模板成功')
        }
        
        // 重新加载模板列表
        await this.loadTemplates()
        this.closeTemplateDesign()
      } catch (error) {
        console.error('保存模板失败:', error)
        alert('保存模板失败，请重试')
      } finally {
        this.loading = false
      }
    },

    // 模板弹窗拖动相关方法
    startDragTemplateModal(event) {
      // 只有点击标题栏区域才能拖动，避免点击关闭按钮时触发拖动
      if (event.target.classList.contains('close-btn')) {
        return
      }
      
      this.templateModalDragging = true
      this.templateModalStartX = event.clientX - this.templateModalOffsetX
      this.templateModalStartY = event.clientY - this.templateModalOffsetY
      
      // 添加全局鼠标事件监听器
      document.addEventListener('mousemove', this.dragTemplateModal)
      document.addEventListener('mouseup', this.stopDragTemplateModal)
      
      // 防止文本选择
      event.preventDefault()
    },

    dragTemplateModal(event) {
      if (!this.templateModalDragging) return
      
      this.templateModalOffsetX = event.clientX - this.templateModalStartX
      this.templateModalOffsetY = event.clientY - this.templateModalStartY
      
      event.preventDefault()
    },

    stopDragTemplateModal() {
      this.templateModalDragging = false
      
      // 移除全局鼠标事件监听器
      document.removeEventListener('mousemove', this.dragTemplateModal)
      document.removeEventListener('mouseup', this.stopDragTemplateModal)
    },

    // 任务块保存后的批量更新事件处理
    handleTaskBlocksUpdated(event) {
      const tasks = event && event.detail && Array.isArray(event.detail.tasks) ? event.detail.tasks : []
      if (!tasks.length) return

      tasks.forEach(savedTask => {
        let deviceConfig = {}
        if (savedTask.daily_device_config) {
          try { deviceConfig = JSON.parse(savedTask.daily_device_config) } catch (e) {}
        }

        const updated = {
          id: savedTask.id,
          name: savedTask.name || savedTask.task_name,
          duration: savedTask.duration,
          color: deviceConfig.color || savedTask.color || '#87CEEB',
          requiredDevices: deviceConfig.devices || savedTask.requiredDevices || [],
          requiredDevice: savedTask.requiredDevice || '',
          deviceCapacities: deviceConfig.deviceCapacities || savedTask.deviceCapacities || {},
          dayConfigs: Array.isArray(deviceConfig.dayConfigs) ? deviceConfig.dayConfigs : (savedTask.dayConfigs || []),
          status: savedTask.status
        }

        // 更新左侧可用任务块列表
        const idx = this.availableTaskBlocks.findIndex(tb => tb.id === updated.id)
        if (idx >= 0) {
          this.$set(this.availableTaskBlocks, idx, { ...this.availableTaskBlocks[idx], ...updated })
        } else {
          this.availableTaskBlocks.push(updated)
        }

        // 同步排列区中对应任务块实例
        this.arrangedTaskBlocks = this.arrangedTaskBlocks.map(task => (
          task.id === updated.id
            ? { ...task, name: updated.name, duration: updated.duration, color: updated.color, requiredDevices: updated.requiredDevices, dayConfigs: updated.dayConfigs }
            : task
        ))
      })
    },

    // 单个任务的按天设备配置变更事件处理（未保存也能实时同步）
    handleTaskBlockDayConfigChanged(event) {
      const detail = event && event.detail ? event.detail : null
      if (!detail || !detail.taskId) return

      const updateFields = {
        name: detail.name,
        duration: detail.duration,
        color: detail.color,
        requiredDevices: Array.isArray(detail.requiredDevices) ? detail.requiredDevices : [],
        dayConfigs: Array.isArray(detail.dayConfigs) ? detail.dayConfigs : []
      }

      // 更新左侧可用任务块
      const idx = this.availableTaskBlocks.findIndex(tb => tb.id === detail.taskId)
      if (idx >= 0) {
        const tb = this.availableTaskBlocks[idx]
        const updated = {
          ...tb,
          name: updateFields.name || tb.name,
          duration: updateFields.duration || tb.duration,
          color: updateFields.color || tb.color,
          requiredDevices: updateFields.requiredDevices,
          dayConfigs: updateFields.dayConfigs
        }
        this.$set(this.availableTaskBlocks, idx, updated)
      }

      // 更新排列区中相关任务块实例
      this.arrangedTaskBlocks = this.arrangedTaskBlocks.map(task => (
        task.id === detail.taskId
          ? {
              ...task,
              name: updateFields.name || task.name,
              duration: updateFields.duration || task.duration,
              color: updateFields.color || task.color,
              requiredDevices: updateFields.requiredDevices,
              dayConfigs: updateFields.dayConfigs
            }
          : task
      ))
    }
  }
}
</script>

<style scoped>
/* 模板配置弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
}

.template-modal {
  width: 700px;
  max-height: 70vh;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
  background-color: #f8f9fa;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.add-template-section {
  margin-bottom: 20px;
}

.add-template-btn {
  background-color: #28a745;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.add-template-btn:hover {
  background-color: #218838;
}

.template-table {
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.table-header {
  display: grid;
  grid-template-columns: 1fr 200px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ddd;
}

.header-cell {
  padding: 12px 16px;
  font-weight: bold;
  text-align: center;
  border-right: 1px solid #ddd;
  font-size: 14px;
}

.header-cell:last-child {
  border-right: none;
}

.template-row {
  display: grid;
  grid-template-columns: 1fr 200px;
  border-bottom: 1px solid #eee;
}

.template-row:last-child {
  border-bottom: none;
}

.cell {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #eee;
}

.cell:last-child {
  border-right: none;
}

.template-number {
  font-weight: bold;
  color: #333;
}

.template-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-btn {
  border: none;
  padding: 6px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.2s;
}

.edit-btn {
  background: #6c757d;
  color: white;
}

.edit-btn:hover {
  background: #545b62;
}

.copy-btn {
  background: #17a2b8;
  color: white;
}

.copy-btn:hover {
  background: #138496;
}

.delete-btn {
  background: #dc3545;
  color: white;
}

.delete-btn:hover {
  background: #c82333;
}

.empty-template {
  padding: 40px 20px;
  text-align: center;
  color: #666;
  font-style: italic;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #eee;
  background-color: #f8f9fa;
}

.cancel-btn {
  background-color: #6c757d;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn:hover {
  background-color: #545b62;
}

.save-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
}

.save-btn:hover {
  background-color: #0056b3;
}

/* 模板设计界面样式 */
.template-design-modal {
  width: 90%;
  max-width: 1200px;
  height: 90vh;
  position: relative;
}

.draggable-header {
  cursor: move;
  user-select: none;
}

.template-design-body {
  display: flex;
  height: calc(90vh - 120px);
  padding: 0;
}

.task-blocks-panel {
  width: 450px;
  border-right: 1px solid #ddd;
  display: flex;
  flex-direction: column;
}

.arrangement-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding: 15px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #ddd;
}

.panel-header h4 {
  margin: 0;
  color: #333;
}

.task-blocks-list {
  padding: 15px;
  overflow-y: auto;
  flex: 1;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  align-content: start;
}

.task-block-item {
  background: #f0f8ff;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 11px;
  cursor: grab;
  transition: all 0.2s;
  min-height: 90px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.task-block-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.task-block-item:active {
  cursor: grabbing;
}

.task-block-name {
  font-weight: bold;
  margin-bottom: 4px;
  font-size: 13px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #000 !important;
}

.task-block-duration,
.task-block-device {
  font-size: 12px;
  color: #666;
  line-height: 1.3;
}

.empty-task-blocks {
  text-align: center;
  color: #999;
  padding: 40px 20px;
  font-style: italic;
}

.arrangement-area {
  padding: 15px;
  overflow-y: auto;
  flex: 1;
  min-height: 200px;
  background: #fafafa;
  scroll-behavior: smooth;
}

.arranged-task-item {
  background: #e3f2fd;
  border: 1px solid #90caf9;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  position: relative;
  cursor: grab;
  transition: all 0.2s;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.arranged-task-item:hover {
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.arranged-task-item:active {
  cursor: grabbing;
}

.task-info {
  flex: 1;
}

.task-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.task-duration,
.task-device {
  font-size: 12px;
  color: #666;
}

.remove-task-btn {
  background: #dc3545;
  color: white;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-task-btn:hover {
  background: #c82333;
}

.drop-hint {
  color: #999;
  font-size: 16px;
  text-align: center;
  padding: 40px;
  border: 2px dashed #ccc;
  border-radius: 8px;
  background: white;
  margin: 20px 0;
}

/* 插入位置指示器 */
.insert-indicator {
  height: 3px;
  background: #007bff;
  margin: 5px 0;
  border-radius: 2px;
  position: relative;
  animation: pulse 1s infinite;
}

.insert-indicator::before {
  content: '';
  position: absolute;
  left: -6px;
  top: -3px;
  width: 9px;
  height: 9px;
  background: #007bff;
  border-radius: 50%;
}

.insert-indicator::after {
  content: '';
  position: absolute;
  right: -6px;
  top: -3px;
  width: 9px;
  height: 9px;
  background: #007bff;
  border-radius: 50%;
}

@keyframes pulse {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}

/* 模板名字编辑样式 */
.template-name {
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 3px;
  transition: background-color 0.2s;
}

.template-name:hover {
  background-color: #f0f0f0;
  text-decoration: underline;
}

.template-name-edit {
  display: flex;
  align-items: center;
  gap: 8px;
}

.template-name-input {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 14px;
  min-width: 120px;
  flex: 1;
}

.template-name-input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.save-name-btn {
  background: none;
  border: 1px solid #28a745;
  border-radius: 3px;
  padding: 2px 6px;
  cursor: pointer;
  font-size: 12px;
  min-width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #28a745;
}

.save-name-btn:hover {
  background-color: #28a745;
  color: white;
}
</style>
